from django.contrib.auth.models import User
from django.core.cache import cache
from django.db import models

from utils.models import BaseModel


# Create your models here.


class NavCategory(BaseModel):
    """
    导航分类
    """

    name = models.CharField(max_length=20,verbose_name="导航名称")
    display_name = models.CharField(max_length=20,verbose_name="导航显示名称")
    weight = models.IntegerField(default=0,verbose_name="权重")
    external_link = models.URLField(verbose_name="外链地址",blank=True)


    class Meta:
        verbose_name = "导航分类"
        verbose_name_plural = verbose_name
        db_table = "tb_nav_category"
        ordering = ["weight"]

    def __str__(self):
        return self.name


class CourseCategory(BaseModel):
    """
    课程分类
    """
    name = models.CharField(max_length=20,verbose_name="课程分类名称")
    level = models.IntegerField(verbose_name="课程分类级别")
    description  = models.TextField(verbose_name="课程分类描述",null=True,blank=True)
    parent = models.ForeignKey('self',on_delete=models.CASCADE,null=True,blank=True,verbose_name="父级分类")

    class Meta:
        verbose_name = "课程分类"
        verbose_name_plural = verbose_name
        db_table = "tb_course_category"

    def __str__(self):
       return self.name


class Banner(BaseModel):

    title = models.CharField(max_length=100,verbose_name="广告标题")
    image = models.CharField(max_length=200,verbose_name="轮播图路径")
    link = models.URLField(max_length=200,verbose_name="轮播图链接")
    note= models.CharField(max_length=100,verbose_name="广告备注")


    class Meta:
        verbose_name = "轮播图"
        verbose_name_plural = verbose_name
        db_table = "tb_banner"
    def __str__(self):
        return self.title



    def save(self, *args, **kwargs):
        """
        重写save方法,在保存数据时,自动清除缓存
        :param args:
        :param kwargs:
        :return:
        """
        super().save(*args, **kwargs)


        #清楚缓存
        cache_key = "code_env_space:home:banner:list"
        cache.delete(cache_key)


    def delete(self, *args, **kwargs):
        """
        重写delete方法,在删除数据时,自动清除缓存
        :param args:
        :param kwargs:
        :return:
        """
        print(self)
        print("删除数据")
        super().delete(*args, **kwargs)

        # 清除缓存
        cache_key = "code_env_space:home:banner:list"
        cache.delete(cache_key)
